/**************************************************************
 * Project	: MCFISH公共库文件
 * Author	: damonyu
 * Modify	: 2017-07-25
 * Comment	: 此函数封装各种常用的公共库文件
**************************************************************/
var mysql		= require('mysql');
var http		= require('http');
var schedule 	= require("node-schedule");
//日志模块
var logger = require('log4js').getLogger("index");

//缓存失败sql，定时再次执行
var failSql = {};

/**************************************************************
* 模块配置
**************************************************************/
module.exports 	= mcfish;
function mcfish(){
	this.mysql	= mysql;
	this.pool	= null;
}
/**
 * 延时操作（ms）
 * @param {*} time
 */
function sleep(time = 0) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve();
      }, time);
    })
}
/**************************************************************
* @brief 数据库相关的操作
**************************************************************/
mcfish.init	= function(PoolOption){
	this.PoolOption = PoolOption
	this.pool		= mysql.createPool(PoolOption);
	this.MqttServer = null;
	this.TcpServer	= null;
	logger.info('-----pool is init-----');
};

/**
 * @brief 数据库查询
*/
mcfish.mysql_query = function(sql, callback){
	// logger.info('[ sql ] sql=' + sql);
	try {
		this.pool.getConnection(function(err, connection) {
			connection.query(sql, function (err, rows, fields) {
				connection.release();
				if (err){
					logger.error('[ sql ] sql=' + sql);
					logger.error(err.stack || err);
					failSql[sql] = sql;
					logger.error(failSql);
					return;
				}
				if (callback != undefined){
					callback(err, rows, fields);
				}
			})
		});
	} catch (error) {
		logger.error('[ sql ] sql=' + sql);
		if(failSql[sql]==null){
			failSql[sql] = sql;
		}
		logger.error(error);
	}
};

/**
 * @brief 关闭所有连接
*/
mcfish.mysql_close = function(sql, callback){
	this.pool.end();
};


/**************************************************************
* @brief 向HTTP服务器回复一条消息
**************************************************************/
mcfish.http_response = function http_reponse(res, code, msg){
	res.writeHead(code, {
		"Content-Type": "text/plain;charset=utf-8"
	});
	res.end(msg);
};

/**************************************************************
* @brief 用TCP向终端发送消息
**************************************************************/
mcfish.send_device_tcp = function send_device_tcp(socket, data){
	socket.write(data);
}


mcfish.send_device_tcp_woshi = function send_device_tcp_woshi(socket, data) {
	mcfish.send_device_tcp(socket, Buffer.from(Str2Bytes(data)))
}


function Str2Bytes(str) {
	var pos = 0;
	var len = str.length;
	if (len % 2 != 0) {
		return null;
	}
	len /= 2;
	var hexA = new Array();
	for (var i = 0; i < len; i++) {
		var s = str.substr(pos, 2);
		var v = parseInt(s, 16);
		hexA.push(v);
		pos += 2;
	}
	return hexA;
}
































